﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using FluentValidation;
using LINQPad.OpenAccess.Helpers;
using LINQPad.OpenAccess.Infrastructure;

namespace LINQPad.OpenAccess.UI.Services
{
    /// <summary>
    ///   <see cref="IValidatorFactory" /> implementation based on the <see cref="IServiceLocator" />.
    /// </summary>
    public class ServiceLocatorBasedValidatorFactory : IValidatorFactory
    {
        #region Private

        #region - Vars

        [DebuggerBrowsable( DebuggerBrowsableState.Never )]
        private readonly IServiceLocator _serviceLocator;

        #endregion

        #endregion

        #region Public

        #region - Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceLocatorBasedValidatorFactory" /> class.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        public ServiceLocatorBasedValidatorFactory( IServiceLocator serviceLocator )
        {
            Guard.ArgumentNotNull( serviceLocator, "serviceLocator" );
            this._serviceLocator = serviceLocator;
        }

        #endregion

        #endregion

        #region IValidatorFactory Members

        /// <summary>
        /// Gets the validator for the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// The validator or <c>null</c>.
        /// </returns>
        public IValidator GetValidator( Type type )
        {
            Guard.ArgumentNotNull( type, "type" );

            return this._serviceLocator.TryGet( typeof( IValidator<> ).MakeGenericType( type ) ) as IValidator;
        }
        /// <summary>
        /// Gets the validator.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>
        /// The validator or <c>null</c>.
        /// </returns>
        public IValidator<T> GetValidator<T>( )
        {
            return this._serviceLocator.TryGet<IValidator<T>>( );
        }

        #endregion
    }
}
